const express = require('express');
const router = express.Router();
const sqlQuery = require('../lcSql');
const jiami = require('../md5');

// 获取登录页面
router.get('/', (req, res) => {
    res.render('login');
});

// 处理登录请求
router.post('/', async (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    let saved = req.body.saved;

    // 构造查询语句
    let sqlStr = "SELECT * FROM users WHERE username = ? AND password = ?";
    // 加密密码
    let encryptedPassword = jiami.md5(password + jiami.salt);

    // 执行查询
    let result = await sqlQuery(sqlStr, [username, encryptedPassword]);

    // 检查结果
    if (result.length > 0) {
        // 登录成功
        req.session.isLoggedIn = true;
        req.session.username = username; // 保存用户名到 session

        // console.log('login success:'+req.session.username+' '+req.session.isLoggedIn);
        
        if (!saved) {
            req.session.cookie.maxAge = 10 * 60 * 1000; // 设置 session 过期时间
        }
        res.json({ status: 'success', message: '登录成功', redirect: '/' });
    } else {
        // 登录失败
        res.json({ status: 'error', message: '账号或密码错误', redirect: '/login' });
    }
});

module.exports = router;
